package com.Controller.Struts.Action;

import com.Controller.Struts.ModelDriven.LoginUser;
import com.Model.DengLuModel.PanDuanZhangHao;
import com.Model.Pojo.LoginRecord;
import com.Model.Pojo.Users;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginAction extends ActionSupport implements ModelDriven<LoginUser>{

    private LoginUser loginUser = new LoginUser();
    @Override
    public LoginUser getModel() {
        return loginUser;
    }

    public String execute() throws IOException {
        String loginResult;//Struts2拦截器还没实现，先这样写，以后再改
        ActionContext actionContext = ActionContext.getContext(); //获取上下文
        HttpServletRequest request =(HttpServletRequest)actionContext.get(ServletActionContext.HTTP_REQUEST);//获取request
        HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
        HttpSession session = request.getSession(false);//获取session
        String name = request.getParameter("userid"); //获取账号密码身份信息
        String pass = request.getParameter("passwordinput");
        String shenfen = request.getParameter("shenfen");
        String url = request.getParameter("url");
        LoginRecord loginRecord = new LoginRecord();
        loginRecord.setLogin_IP(loginRecord.getIpAddr(request)); //获取用户IP存入登录记录中

        //实例化判断账号密码的对象
        PanDuanZhangHao panduan = new PanDuanZhangHao(name, pass, shenfen);
        String flag = panduan.panDuan(); //第二次判断账号密码是否正确
        if(flag.equals("false")){
            loginResult = Action.ERROR;
            response.sendRedirect(url); //返回之前的页面。0//因为拦截器还不行，所以就先用这个跳转
        }else{
            Users users = panduan.getUsersByNameOrShoujihaoOrYouxiang(flag,name,pass);//根据对应的输入的信息获取用户的详细信息
            //System.out.println(users.getZhanghao()+users.getMima()+users.getYue()+users.getMoney());
            session.setAttribute("users", users); //把user存在session里面
            loginRecord.setUserLoginRecord(users.getZhanghao(), shenfen);//该用户的登录记录写入数据库中
            loginResult = Action.SUCCESS;
            response.sendRedirect(url); //返回之前的页面。
        }
        return loginResult;
    }
}
